package com.jiaai.shop.store.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jiaai.shop.store.entity.SMember;
import com.jiaai.shop.store.entity.TIntegralHistory;
import com.jiaai.shop.store.entity.TMemberGoods;
import com.jiaai.shop.store.service.ISMemberService;
import com.jiaai.shop.store.service.ITIntegralHistoryService;
import com.jiaai.shop.store.service.ITMemberGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@EnableScheduling
public class TimingUtil {

    @Autowired
    private ISMemberService isMemberService;

    @Autowired
    private ITMemberGoodsService memberGoodsService;

    @Autowired
    private ITIntegralHistoryService integralHistoryService;

    /**
     * 定时触发
     * 星期一到星期五每天0点0分0秒给客户返积分
     * */
    @Scheduled(cron = "0 0 0 ? * MON-FRI")
    public void todayAddInter(){
        List<TMemberGoods> memberGoods=null;
        EntityWrapper wrapper=new EntityWrapper();
        wrapper.ge("integralEffectivetime",new Date());
        memberGoods=memberGoodsService.selectList(wrapper);
        Map<String,List<TMemberGoods>> map=new HashMap<>();
        if(memberGoods!=null && memberGoods.size()>0){
             memberGoods.forEach((v)->{
                 if(map.containsKey(v.getmId())){
                     map.get(v.getmId()).add(v);
                 }else {
                     List<TMemberGoods> mg=new ArrayList<>();
                     mg.add(v);
                     map.put(v.getmId(),mg);
                 }
             });
        }
        map.keySet().forEach((k)->{
            final int[] totalIntegral = {0};
            SMember member=isMemberService.selectById(k);

             map.get(k).forEach((item)->{
                   totalIntegral[0] +=item.getIntegral();
             });
            member.setPresentScore(member.getInviterNumber()+totalIntegral[0]);
            member.setTotalScore(member.getTotalScore()+totalIntegral[0]);
            TIntegralHistory integralHistory=new TIntegralHistory();
            integralHistory.setDescribe("获得系统返佣奖励"+totalIntegral[0]+"积分");
            integralHistory.setMemberId(member.getMemberId());
            integralHistory.setType(2);
            integralHistory.setNum(totalIntegral[0]);
            integralHistory.setTime(new Date());
            integralHistoryService.insert(integralHistory);
            isMemberService.updateById(member);
        });

    }
}
